<style scoped>
  .clientSalesAnalysis {
    margin-right: 0.5vw;
    padding: 0 15px;
    background-color: white;
    height: 95vh;
    position: relative;
  }
  .csa_top{
    display: flex;
    padding: 1.5vh 0;
    border-bottom: 2px solid #f4f4f4;
  }
  .csa_top p:first-child{
    margin: 3px 6px 0 0;
    white-space: nowrap;
  }
  .csa_top p:not(:first-child){
    margin: 3px 6px 0 12px;
    white-space: nowrap;
  }
  .csa_button{
    padding: 1.5vh 0;
  }
  .csa_tab{
    display: flex;
  }
  .csa_tab div{
    width: 49%;
  }
  .csa_tab2{
    margin-top: 1.5vh;
    border-top: 1vh solid #f4f4f4;
  }
  .tab2_top{
    height: 40px;
    border-bottom: 2px solid #f4f4f4;
    padding: 7px 15px 0 15px;
    justify-content: space-between;
    display: flex;
  }
  .tab2_top>div:first-child{
    display: flex;
  }
  .tab2_top1{
    width: 5px;
    height: 20px;
    background: #017fff;
    margin: 2px 5px;
  }
  .tab2_top div:last-child{
    display: flex;
  }
  .border1{
    width: 13px;
    height: 13px;
    margin: 5px 20px 0 50px;
    background: green;
    border-radius: 50%;
  }
  .border2{
    width: 13px;
    height: 13px;
    margin: 5px 20px 0 50px;
    background: blue;
    border-radius: 50%;
  }
  .footView span{
    float: left;
    margin-right: 48px;
    line-height: 6vh;
    font-size: 14px;
  }
  .footView span i{
    margin-right: 5px;
  }
</style>

<style>
  .clientSalesAnalysis .el-input__icon{
    line-height: 30px;
  }
  .clientSalesAnalysis .el-input__inner{
    height: 30px;
  }
  .clientSalesAnalysis .block .el-date-editor .el-range-separator{
    line-height: 23px;
  }
  .clientSalesAnalysis .block .el-date-editor .el-range__icon{
    line-height: 23px;
  }
  .clientSalesAnalysis .block .el-date-editor .el-range-separator{
    padding: 0;
  }
  .clientSalesAnalysis .el-checkbox.is-bordered{
    height: 30px;
    padding: 4px 10px 0px 10px;
    margin-left: 12px;
  }

  .clientSalesAnalysis .el-radio--small.is-bordered{
    padding: 6px 15px 0 10px;
    height: 26px;
  }

  .clientSalesAnalysis .el-table .cell {
    padding:0 0 0 5px;
  }
</style>

<template>
  <div class="clientSalesAnalysis">
    <div class="csa_top">
      <p>日期</p>
      <div class="block">
        <span class="demonstration"></span>
        <el-date-picker 
          unlink-panels
          v-model="dateList" 
          style="width:300px" 
          type="daterange" 
          range-separator="至" 
          start-placeholder="开始日期" 
          end-placeholder="结束日期" 
          value-format="yyyy-MM-dd"></el-date-picker>
      </div>
      <p>季度</p>
      <el-select v-model="quarter" multiple collapse-tags style="width:8vw;">
        <el-option v-for="item in quarterList" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <p>地区</p>
      <el-select v-model="area" multiple collapse-tags style="width:8vw;">
        <el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item.name"></el-option>
      </el-select>
      <p>业务</p>
      <el-select v-model="business" multiple collapse-tags style="width:8vw;">
        <el-option v-for="item in businessList" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <p>客户</p>
      <el-select v-model="customer" style="width:8vw;" :disabled="jxAgent">
        <el-option v-for="item in customerList" :key="item.value" :label="item.label" :value="item.value">
          <span style="float:left">{{item.value}}</span>
          <span style="float:right">{{item.label}}</span></el-option>
      </el-select>
      <p>总店</p>
      <el-select v-model="headOfficeNumber" style="width:8vw;">
        <el-option v-for="item in headOfficeNumberList" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <p>组合</p>
      <el-select multiple collapse-tags clearable v-model="assembly" style="width:140px;">
        <el-option v-for="item in assemblyList" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <el-checkbox v-model="checked" border>横向</el-checkbox></div>
    <div class="csa_button">
      <el-button @click="search" icon="el-icon-search" type="primary">查询</el-button>
      <el-button @click="exportExcel" icon="el-icon-upload2">导出</el-button></div>
    <div class="csa_tab">
      <div style="margin-right:1vw">
        <el-table id="outTable" 
          height="38vh" 
          :data="tableData1" 
          show-summary 
          :summary-method="getSummaries"
          ref="table"
          :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}" 
          :cell-style="{padding:0,height:'36px'}" 
          style="width: 100%;">
          <template v-for="i in hList">
            <el-table-column
              :prop="i.prop"
              :label="i.label"
              :width="i.width"
              :key="i.prop"
              v-if="i.isShow">
            </el-table-column>
          </template>
        </el-table>
      </div>
      <div>
        <el-table height="38vh" 
          :data="tableData2" 
          :header-cell-style="{background:'#f4f4f4',padding:0,height:'40px'}" 
          :cell-style="{padding:0,height:'36px'}" 
          style="width: 100%;">
          <el-table-column prop="quarter" label="季度"></el-table-column>
          <el-table-column prop="number" label="数量"></el-table-column>
          <el-table-column prop="sellMoney" label="售价金额"></el-table-column>
          <el-table-column prop="actualMoney" label="实收金额"></el-table-column>
        </el-table>
      </div>
    </div>
    <div class="csa_tab2">
      <div class="tab2_top">
        <div>
          <div class="tab2_top1"></div>
          <p>年度月份销售对应折线图</p>
        </div>
        <div>
          <el-radio-group v-model="radio" size="small">
            <el-radio label="1" border>数量</el-radio>
            <el-radio label="2" border>金额</el-radio>
          </el-radio-group>
        </div>
        <!-- <div>
          <div class="border1"></div>
          <p>2019年：277</p>
          <div class="border2"></div>
          <p>2020年：21376</p>
        </div> -->
      </div>
      <div>
        <ve-line 
          :data="chartData" 
          :extend="extend"
          height="35vh" 
          :settings="chartSettings"></ve-line>
      </div>
    </div>

    <foot-view class="footView">
      <div slot="text">
        <span>数据库：{{jxQuarter}}</span>
        <span>记录数：{{amount}}</span>
      </div>
    </foot-view>
  </div>
</template>

<script>
import footView from '../../../components/FootView'

import { getCustomerSellStatistics } from '../../../network/customerQuery'
import { getClient } from '../../../network/client'
import { getQuarter } from '../../../network/quarter'
import { getClerk } from '../../../network/clerk'

import XLSX from "xlsx"
import FileSaver from "file-saver"

import {provincea} from '../../../config/address'

import today from '../../../components/mixins/today'
import enterUp from '../../../components/mixins/enterUp'
import zero from '../../../components/mixins/zero2blank'

export default {
  name: 'client_sales_analysis',
  mixins: [today,enterUp, zero],
  created(){
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    let jxAgentVal = document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))
    let operatorVal = document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null
    this.operator = operatorVal ? operatorVal[1] : null
   if(jxAgentVal){
    this.jxAgent = jxAgentVal[1] == 1 ? true : false
   }

    this.inpList = this.getInput()
    this.hList = this.hList1
    this.areaList = provincea
    this.dateList = [this.searchDate(730),this.searchDate()]
    // 获取所有客户信息
    this.customerList = []
    getClient({limit:99999}).then(res => {
      if (res.data.code == 200) {
        let list = res.data.data
        list.forEach(e => {
          this.customerList.push({value:e.no,label:e.name})
          if (!this.headOfficeNumberList.length) {
            this.headOfficeNumberList.push({value:e.headquartersNo,label:e.headquartersNo})
          } else {
            let exist = 0
            for (const i of this.headOfficeNumberList) {
              exist = 0
              if (e.headquartersNo == i.value) {
                exist = 1
                break
              }
            }
            if (!exist) {
              this.headOfficeNumberList.push({value:e.headquartersNo,label:e.headquartersNo})
            }
          }
        })
        if (this.jxAgent) {
          for (const i of this.customerList) {
            if (i.label == this.operator) {
              this.customer = [i.value]
              break
            }
          }
        }
      }
    })

    // 获取季度
    getQuarter().then(res => {
      if (res.data.code == 200) {
        res.data.data.forEach(e => {
          this.quarterList.push({value:e.name,label:e.name})
        })
      }
    })

    // 获取业务
    getClerk().then(res=>{
      let list = res.data.data
      list.forEach(element => { 
        if (element.department == '业务') {
          this.businessList.push({label:element.name,value:element.name})
        }
      })
    })
  },
  components:{
    footView
  },
  data(){
    this.extend = {
      series: {
        type: 'line',
        label: {
          normal: {
            show: true
          }
        }
      }
    }
    this.chartSettings = {
      labelMap: {},
      legendName: {}
    }
    return{
      inpList: [],
      dateList: null,
      quarter: [],
      quarterList: [],
      area: [],
      areaList: [],
      business: [],
      businessList: [],
      customer: [],
      customerList: [],
      headOfficeNumber: [],
      headOfficeNumberList: [],
      assembly: ['1','2','3','4'],
      assemblyList: [
        {value: '1', label: '年'},
        {value: '2', label: '月'},
        {value: '3', label: '季度'},
        {value: '4', label: '部类'},
      ],
      checked: false,
      tableData1: [],
      leftTable1: [],
      leftTable2: [],
      tableData2: [],

      hList: [],
      hList1: [
        {prop:'year',label:'年度',width:'80',isShow:true},
        {prop:'month',label:'月份',width:'60',isShow:true},
        {prop:'quarter',label:'季度',width:'',isShow:true},
        {prop:'commodityType',label:'部类',width:'60',isShow:true},
        {prop:'number',label:'数量',width:'',isShow:true},
        {prop:'sellMoney',label:'售价金额',width:'',isShow:true},
        {prop:'actualMoney',label:'实收金额',width:'',isShow:true},
      ],
      hList2: [
        {prop:'year',label:'年度',width:'60',isShow:true},
        {prop:'1',label:'01',width:'54',isShow:true},
        {prop:'2',label:'02',width:'54',isShow:true},
        {prop:'3',label:'03',width:'54',isShow:true},
        {prop:'4',label:'04',width:'54',isShow:true},
        {prop:'5',label:'05',width:'54',isShow:true},
        {prop:'6',label:'06',width:'54',isShow:true},
        {prop:'7',label:'07',width:'54',isShow:true},
        {prop:'8',label:'08',width:'54',isShow:true},
        {prop:'9',label:'09',width:'54',isShow:true},
        {prop:'10',label:'10',width:'54',isShow:true},
        {prop:'11',label:'11',width:'54',isShow:true},
        {prop:'12',label:'12',width:'54',isShow:true},
        {prop:'total',label:'月份合计',width:'',isShow:true},
      ],

      amount: 0,
      radio: '1',
      chartData: {
        columns: ['date' ],
        rows: [
          { 'date': '1月' },
          { 'date': '2月' },
          { 'date': '3月' },
          { 'date': '4月' },
          { 'date': '5月' },
          { 'date': '6月' },
          { 'date': '7月' },
          { 'date': '8月' },
          { 'date': '9月' },
          { 'date': '10月' },
          { 'date': '11月' },
          { 'date': '12月' }
        ]
      },
      yearList: [],
      jxQuarter: null,
      jxAgent:null,
      operator:null,
      // jxQuarter: document.cookie.match(RegExp('jxQuarter'+'=([^;]+)'))[1],
      // jxAgent: document.cookie.match(RegExp('jxAgent'+'=([^;]+)'))[1] == 1 ? true : false,
      // operator: document.cookie.match(RegExp('jxUser'+'=([^;]+)'))[1]
    }
  },
  watch: {
    assembly(a,b){
      if (a.length) {
        if (a.indexOf('1') == -1) {
          this.hList1[0].isShow = false
        } else {
          this.hList1[0].isShow = true
        }
        if (a.indexOf('2') == -1) {
          this.hList1[1].isShow = false
        } else {
          this.hList1[1].isShow = true
        }
        if (a.indexOf('3') == -1) {
          this.hList1[2].isShow = false
        } else {
          this.hList1[2].isShow = true
        }
        if (a.indexOf('4') == -1) {
          this.hList1[3].isShow = false
        } else {
          this.hList1[3].isShow = true
        }
      } else {
        this.hList1[0].isShow = false
        this.hList1[1].isShow = false
        this.hList1[2].isShow = false
        this.hList1[3].isShow = false
      }
    },
    checked(a,b){
      if (a) {
        this.hList = this.hList2
        this.tableData1 = this.leftTable2
      } else {
        this.hList = this.hList1
        this.tableData1 = this.leftTable1
      }
    },
    radio(a,b){
      if (a == 2) {
        // 金额
        this.switchChart(1)
      } else {
        // 数量
        this.switchChart(0)
      }
    }
  },
  methods: {
    // 导出
    exportExcel(){
      let xlsxParam = { raw: true }  //转换成excel时，使用原始的格式
      let wb = XLSX.utils.table_to_book(document.querySelector("#outTable"),xlsxParam);
      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),
          "客户销售分析.xlsx"
        )
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout)
      }
      return wbout
    },

    search(){
      let pq = ''
      if (this.quarter.length) {
        for (const e of this.quarter) {
          if (pq == '') {
            pq = `'${e}'`
            continue
          }
          pq = `${pq},'${e}'`
        }
      }

      let pa = ''
      if (this.area.length) {
        for (const e of this.area) {
          if (pa == '') {
            pa = `'${e}'`
            continue
          }
          pa = `${pa},'${e}'`
        }
      }

      let pb = ''
      if (this.business.length) {
        for (const e of this.business) {
          if (pb == '') {
            pb = `'${e}'`
            continue
          }
          pb = `${pb},'${e}'`
        }
      }

      let pc = ''
      if (this.customer.length) {
        for (const e of this.customer) {
          if (pc == '') {
            pc = `'${e}'`
            continue
          }
          pc = `${pc},'${e}'`
        }
      }

      let ph = ''
      if (this.headOfficeNumber.length) {
        for (const e of this.headOfficeNumber) {
          if (ph == '') {
            ph = `'${e}'`
            continue
          }
          ph = `${ph},'${e}'`
        }
      }

      let params = {
        startTime: this.dateList ? this.dateList[0] + ' 00:00:00' : '',
        endTime: this.dateList ? this.dateList[1] + ' 23:59:59' : '',
        quarter: pq,
        area: pa,
        business: pb,
        customerNo: pc,
        headOfficeNumber: ph,
        combination: String(this.assembly)
      }
      // return
      getCustomerSellStatistics(params).then(res => {
        if (res.data.code == 200) {
          this.radio = '1'
          this.yearList = []
          this.checked = false
          this.leftTable1 = res.data.data.leftTotal
          this.tableData2 = res.data.data.rightTotal
          this.tableData1 = this.leftTable1
          this.chartData = {
            columns: ['date' ],
            rows: [
              { 'date': '1月' },
              { 'date': '2月' },
              { 'date': '3月' },
              { 'date': '4月' },
              { 'date': '5月' },
              { 'date': '6月' },
              { 'date': '7月' },
              { 'date': '8月' },
              { 'date': '9月' },
              { 'date': '10月' },
              { 'date': '11月' },
              { 'date': '12月' }
            ]
          }

          this.amount = res.data.data.leftTotal.length

          if (this.leftTable1.length) {
            let yearExist = 0
            this.leftTable1.forEach(e => {
              e[`${e.year}M`] = e.sellMoney
              e[`${e.year}T`] = e.number
              if (!this.yearList.length) {
                this.yearList.push({year:e.year,total:e.number,money:e.sellMoney})
              } else {
                for (const i of this.yearList) {
                  if (i.year == e.year) {
                    yearExist = 1
                    i.total += e.number
                    i.money += e.sellMoney
                    break
                  }
                  yearExist = 0
                }
                if (!yearExist) {
                  this.yearList.push({year:e.year,total:e.number,money:e.sellMoney})
                }
              }
            })
            // console.log(this.yearList)
            this.leftTable2 = this.switchTable(this.leftTable1)
            this.yearList.forEach(e => {
              this.chartData.rows.forEach(f => {
                f[`${e.year}M`] = 0
                f[`${e.year}T`] = 0
              })
            })
            // console.log(this.chartData)
            this.switchChart(0)
            this.leftTable1.forEach(e => {
              for (const i of this.chartData.rows) {
                if (i.date.indexOf(e.month) != -1) {
                  i[`${e.year}M`] += e.sellMoney
                  i[`${e.year}T`] += e.number
                  break
                }
              }
            })

            this.$nextTick(() => {
              this.$refs.table.doLayout()
            })
          }
        }
      })
    },

    switchChart(f){
      // 0是数量，1是金额
      this.chartData.columns = ['date' ]
      this.yearList.forEach(e => {
        // console.log(e)
        this.chartData.columns.push(f ? `${e.year}M` : `${e.year}T`)
        this.chartSettings.labelMap[f ? `${e.year}M` : `${e.year}T`] = e.year + '年'
        this.chartSettings.legendName[`${e.year}年`] = f ? `${e.year}年：${e.money}` : `${e.year}年：${e.total}`
      })
      // console.log(this.chartSettings)
    },
    switchTable(list){
      let res = []
      this.yearList.forEach(e => {
        res.push({year:e.year,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,total:0})
      })
      list.forEach(e => {
        for (const i of res) {
          // console.log(e)
          // console.log(i)
          if (i.year == e.year) {
            i[e.month] += e.number
            break
          }
        }
      })
      res.forEach(e => {
        e.total = e[1] + e[2] + e[3] + e[4] + e[5] + e[6] + e[7] + e[8] + e[9] + e[10] + e[11] + e[12]
        for (const key in e) {
          if (e.hasOwnProperty(key)) {
            const element = e[key]
            if (!element) e[key] = ''
          }
        }
      })
      
      // console.log(res)
      return res
    },

    getSummaries(param){
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const prop = column.property
        const values = data.map(item => Number(item[prop]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          if (!sums[index]) {
            sums[index] = ''
          }
          let decimal = sums[index].toString().split('.')[1]
          if (decimal && decimal.length > 2) {
            sums[index] = sums[index].toFixed(2)
          }
          if (prop == 'month') {
            sums[index] = ''
          }
        }
      })
      return sums
    }
  }
}
</script>